﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Bussiness;
using System.Data.OleDb;
using System.Data;
using System.IO;

namespace WebApplication.Admin
{
    public partial class KhachHangList : System.Web.UI.Page
    {
        CHUCNANG objchucnang = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            KiemtraQUyenSuDung();
            if (!IsPostBack)
            {
                LoadHienthi();
            }
        }
        public void LoadHienthi()
        {
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            KHACHHANGRepository repository = new KHACHHANGRepository(new EFRepository<KHACHHANG>(), iunitfwork);
            IQueryable<KHACHHANG> Objkhachhang = repository.All();
            GrKhachhang.DataSource = Objkhachhang;
            GrKhachhang.DataBind();
        }

        protected void GrKhachhang_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "lbtnsua")
            {
                Response.Redirect("KhachHangAdd.aspx?MAKH=" + e.CommandArgument);
            }
            if (e.CommandName == "lbtnxoa")
            {
                try
                {
                    IUnitOfWork iunitfwork = new EFUnitOfWork();
                    KHACHHANGRepository repository = new KHACHHANGRepository(new EFRepository<KHACHHANG>(), iunitfwork);
                    KHACHHANG objKhachhang = repository.GetById(e.CommandArgument.ToString());
                    if (objKhachhang != null)
                    {
                        repository.Delete(objKhachhang);
                        repository.Save();
                        LoadHienthi();
                    }
                }
                catch (Exception ex)
                {
                    RegisterClientScriptBlock("Thông báo", "<script> alert('Không thể xóa được')</script>");
                }
            }
        }
        public void KiemtraQUyenSuDung()
        {
            lbtnthemmoi.Visible = false;
            if (Session["MANV"] != null)
            {
                string strMANV = Session["MANV"].ToString();
                IUnitOfWork iunitwork = new EFUnitOfWork();
                lbtnthemmoi.Visible = false;
                NHANVIENRepository repository = new NHANVIENRepository(new EFRepository<NHANVIEN>(), iunitwork);
                NHANVIEN objNhanvien = repository.All().Where(p => p.MANV == strMANV).FirstOrDefault();
                if (objNhanvien != null)
                {
                    objchucnang = Commomcs.QuyenTruyCapChucnang(Request.Url.AbsolutePath, objNhanvien.MANV);
                    if (objchucnang != null)
                    {
                        if (objchucnang.ISADD == true)
                        {
                            lbtnthemmoi.Visible = true;
                        }
                        else
                        {
                            lbtnthemmoi.Visible = false;
                        }

                    }
                }
            }
        }
        protected void GrKhachhang_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex < 0) return;
            KHACHHANG objKhachHang = ((KHACHHANG)e.Row.DataItem);
            if (objKhachHang != null)
            {
               
                Label lbtinhtrang = ((Label)e.Row.FindControl("lbtinhtrang"));
                if (lbtinhtrang != null)
                {
                    if (objKhachHang.TINHTRANG == true)
                    {
                        lbtinhtrang.Text = "Hoạt động";
                    }
                    else
                    {
                        lbtinhtrang.Text = "Không hoạt động";
                    }
                }
            }
            LinkButton lbtnsua = ((LinkButton)e.Row.FindControl("lbtnsua"));
            LinkButton lbtnxoa = ((LinkButton)e.Row.FindControl("lbtnxoa"));
            lbtnsua.Visible = false;
            lbtnxoa.Visible = false;
            if (objchucnang != null)
            {
                if (lbtnsua != null)
                {
                    if (objchucnang.ISEDIT == true)
                    {
                        lbtnsua.Visible = true;
                    }
                    else
                    {
                        lbtnsua.Visible = false;
                    }
                }
                if (lbtnxoa != null)
                {
                    if (objchucnang.ISDELETE == true)
                    {
                        lbtnxoa.Visible = true;
                    }
                    else
                    {
                        lbtnxoa.Visible = false;
                    }
                }
            }
        }

     
        protected void GrKhachhang_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            LoadHienthi();
            GrKhachhang.PageIndex = e.NewPageIndex;
            GrKhachhang.DataBind();
        }

        protected void lbtnthemmoi_Click(object sender, EventArgs e)
        {
            Response.Redirect("KhachHangAdd.aspx");
        }

        protected void lbtncapnhap_Click(object sender, EventArgs e)
        {
            TimKiem();
        }
        public void TimKiem()
        {
            IUnitOfWork iunitfwork = new EFUnitOfWork();
            KHACHHANGRepository repository = new KHACHHANGRepository(new EFRepository<KHACHHANG>(), iunitfwork);
            IQueryable<KHACHHANG> LstKhachhang = null;
            if (!string.IsNullOrEmpty(txtmakh.Value))
            {
                LstKhachhang = repository.All().Where(p =>p.MAKH.Contains(txtmakh.Value));
                GrKhachhang.DataSource = LstKhachhang;
                GrKhachhang.DataBind();
            }
            if (!string.IsNullOrEmpty(txttenkh.Value))
            {
                LstKhachhang = repository.All().Where(p => txttenkh.Value.Contains(p.TENKH));
                GrKhachhang.DataSource = LstKhachhang;
                GrKhachhang.DataBind();
            }
            if (!string.IsNullOrEmpty(txtdiachi.Value))
            {
                LstKhachhang = repository.All().Where(p => txtdiachi.Value.Contains(p.TENKH));
                GrKhachhang.DataSource = LstKhachhang;
                GrKhachhang.DataBind();
            }
            if (!string.IsNullOrEmpty(txtsdt.Value))
            {
                LstKhachhang = repository.All().Where(p => p.SDT.Contains(txtsdt.Value));
                GrKhachhang.DataSource = LstKhachhang;
                GrKhachhang.DataBind();
            }
            if (!string.IsNullOrEmpty(txtmakh.Value) && !string.IsNullOrEmpty(txttenkh.Value))
            {
                LstKhachhang = repository.All().Where(p => p.SDT.Contains(txtsdt.Value) && p.TENKH.Contains(txttenkh.Value));
                GrKhachhang.DataSource = LstKhachhang;
                GrKhachhang.DataBind();
            }
            if (!string.IsNullOrEmpty(txtmakh.Value) && !string.IsNullOrEmpty(txttenkh.Value) && !string.IsNullOrEmpty(txtdiachi.Value))
            {
                LstKhachhang = repository.All().Where(p => p.SDT.Contains(txtsdt.Value) && p.TENKH.Contains(txttenkh.Value) && p.DIACHI.Contains(txtdiachi.Value));
                GrKhachhang.DataSource = LstKhachhang;
                GrKhachhang.DataBind();
            }
            if (!string.IsNullOrEmpty(txtmakh.Value) && !string.IsNullOrEmpty(txttenkh.Value) && !string.IsNullOrEmpty(txtdiachi.Value)&& !string.IsNullOrEmpty(txtsdt.Value))
            {
                LstKhachhang = repository.All().Where(p => p.SDT.Contains(txtsdt.Value) && p.TENKH.Contains(txttenkh.Value) && p.DIACHI.Contains(txtdiachi.Value) && p.SDT.Contains(txtsdt.Value));

                GrKhachhang.DataSource = LstKhachhang;
                GrKhachhang.DataBind();
            }
            if (!string.IsNullOrEmpty(txtdiachi.Value) && !string.IsNullOrEmpty(txtsdt.Value))
            {
                LstKhachhang = repository.All().Where(p => p.DIACHI.Contains(txtdiachi.Value) && p.SDT.Contains(txtsdt.Value));
                GrKhachhang.DataSource = LstKhachhang;
                GrKhachhang.DataBind();
            }
            if (!string.IsNullOrEmpty(txtdiachi.Value) && !string.IsNullOrEmpty(txttenkh.Value))
            {
                LstKhachhang = repository.All().Where(p => p.DIACHI.Contains(txtdiachi.Value) && p.TENKH.Contains(txttenkh.Value));
                GrKhachhang.DataSource = LstKhachhang;
                GrKhachhang.DataBind();
            }
            if(!string.IsNullOrEmpty(txtdiachi.Value) && !string.IsNullOrEmpty(txtsdt.Value))
            {
                LstKhachhang=repository.All().Where(p=>p.DIACHI.Contains(txtdiachi.Value) && p.SDT.Contains(txtsdt.Value));
                GrKhachhang.DataSource = LstKhachhang;
                GrKhachhang.DataBind();
            }
            if (string.IsNullOrEmpty(txtmakh.Value) && string.IsNullOrEmpty(txttenkh.Value) && string.IsNullOrEmpty(txtdiachi.Value) && string.IsNullOrEmpty(txtsdt.Value))
            {
                LstKhachhang = repository.All();
                GrKhachhang.DataSource = LstKhachhang;
                GrKhachhang.DataBind();
            }
        }



        protected void btnimport_Click(object sender, EventArgs e)
        {
            if (FileUpload1.PostedFile.ContentType == "application/vnd.ms-excel" ||
        FileUpload1.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                try
                {
                string fileName = Path.Combine(Server.MapPath("~/Admin/ImportDocument"), Guid.NewGuid().ToString() + Path.GetExtension(FileUpload1.PostedFile.FileName));
                FileUpload1.PostedFile.SaveAs(fileName);

                string conString = "";
                string ext = Path.GetExtension(FileUpload1.PostedFile.FileName);
                if (ext.ToLower() == ".xls")
                {
                    conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; ;
                }
                else if (ext.ToLower() == ".xlsx")
                {
                    conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                }

                string query = "Select [Makh],[Makv],[Tenkh],[SoTaikhoan],[NganHang],[MaSoThue],[DiaChi],[SDT],[Fax],[Website],[Yahoo] ,[Sky],[TinhTrang],[GiaBan],[Manh] from [DanhSachKhachHang$]";
                OleDbConnection con = new OleDbConnection(conString);
                if (con.State == System.Data.ConnectionState.Closed)
                {
                    con.Open();
                }
                OleDbCommand cmd = new OleDbCommand(query, con);
                OleDbDataAdapter da = new OleDbDataAdapter(cmd);

                DataSet ds = new DataSet();
                da.Fill(ds);
                da.Dispose();
                con.Close();
                con.Dispose();

                // Import to Database
                using (XUAT_NHAPTONEntities dc = new XUAT_NHAPTONEntities())
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        string empID = dr["Makh"].ToString();
                        var v = dc.KHACHHANGs.Where(a => a.MAKH.Equals(empID)).FirstOrDefault();
                        if (v != null)
                        {
                            // Update here
                            v.MAKH = dr["Makh"].ToString();
                            v.MAKV = dr["Makv"].ToString();
                            v.TENKH = dr["Tenkh"].ToString();
                            v.SOTAIKHOAN = dr["SoTaikhoan"].ToString();
                            v.NGANHANG = dr["NganHang"].ToString();
                            v.MASOTHUE = dr["MaSoThue"].ToString();
                            v.DIACHI = dr["DiaChi"].ToString();
                            v.SDT = dr["SDT"].ToString();
                            v.FAX = dr["Fax"].ToString();
                            v.WEBSITE = dr["Website"].ToString();
                            v.YAHOO = dr["Yahoo"].ToString();
                            v.SKYPE = dr["Sky"].ToString();
                            v.TINHTRANG = (bool)(dr["TinhTrang"]);
                            v.GIABAN = dr["GiaBan"].ToString();
                            v.MANH = dr["Manh"].ToString();

                        }
                        else
                        {
                            // Insert
                            dc.KHACHHANGs.AddObject(new KHACHHANG
                            {
                                MAKH = dr["Makh"].ToString(),
                                MAKV = dr["Makv"].ToString(),
                                TENKH = dr["Tenkh"].ToString(),
                                SOTAIKHOAN = dr["SoTaiKhoan"].ToString(),
                                NGANHANG = dr["NganHang"].ToString(),
                                MASOTHUE = dr["MaSoThue"].ToString(),
                                DIACHI = dr["DiaChi"].ToString(),
                                SDT = dr["SDT"].ToString(),
                                FAX = dr["Fax"].ToString(),
                                WEBSITE = dr["Website"].ToString(),
                                YAHOO = dr["Yahoo"].ToString(),
                                SKYPE = dr["Sky"].ToString(),
                                TINHTRANG = (bool)(dr["TinhTrang"]),
                                GIABAN = dr["GiaBan"].ToString(),
                                MANH = dr["Manh"].ToString()
                            });
                        }
                    }

                    dc.SaveChanges();
                    LoadHienthi();
                        }
                    }
                    catch (Exception ex)
                    {
                        RegisterClientScriptBlock("Thông báo", "<script> alert('Lỗi rồi Import lại')</script>");
                    }
                }
            
        }

        protected void GrKhachhang_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {

        }
    }
    
}